/*
 * Copyright (C) 2010 Wim Crols <twimpiex@gnx.be>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package be.gnx.event.consumer.receiver.net;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import be.gnx.event.consumer.receiver.EventProcessor;
import be.gnx.event.consumer.receiver.Receiver;

public class SocketListener extends Receiver {

	private final int port;

	private final int backlog;

	private final InetAddress inetAddress;

	private ServerSocket serverSocket;

	public SocketListener(int port, int backlog, InetAddress inetAddress,
			EventProcessor eventProcessor) {
		super(eventProcessor);
		this.port = port;
		this.backlog = backlog;
		this.inetAddress = inetAddress;
	}

	@Override
	public void run() {
		try {
			serverSocket = new ServerSocket(port, backlog, inetAddress);
			serverSocket.setReuseAddress(true);
			while (true) {
				final Socket socket = serverSocket.accept();
				final Thread thread = new Thread(new AcceptedSocket(socket,
						this, getEventProcessor()));
				thread.setDaemon(true);
				thread.start();
			}
		} catch (IOException ioException) {
			System.err.println(ioException);
		}
	}

	public boolean isClosed() {
		return serverSocket == null || serverSocket.isClosed();
	}

}
